/**
 * 初始化
 */
const Init = (function () {

    let Init = function () {};

    // 图片幻灯片
    window.initPhotoSwipeFromElements = function(galleryElements) {

        // parse slide data (url, title, size ...) from DOM elements
        // (children of gallerySelector)
        var parseThumbnailElements = function(el) {
            var thumbElements = el.childNodes,
                numNodes = thumbElements.length,
                items = [],
                figureEl,
                linkEl,
                size,
                item;

            for(var i = 0; i < numNodes; i++) {

                figureEl = thumbElements[i]; // <figure> element

                // include only element nodes
                if(figureEl.nodeType !== 1) {
                    continue;
                }

                linkEl = figureEl.children[0]; // <a> element

                size = linkEl.getAttribute('data-size').split('x');

                // create slide object
                item = {
                    src: linkEl.getAttribute('href'),
                    w: parseInt(size[0], 10),
                    h: parseInt(size[1], 10)
                };



                if(figureEl.children.length > 1) {
                    // <figcaption> content
                    item.title = figureEl.children[1].innerHTML;
                }

                if(linkEl.children.length > 0) {
                    // <img> thumbnail element, retrieving thumbnail url
                    item.msrc = linkEl.children[0].getAttribute('src');
                }

                item.el = figureEl; // save link to element for getThumbBoundsFn
                items.push(item);
            }

            return items;
        };

        // find nearest parent element
        var closest = function closest(el, fn) {
            return el && ( fn(el) ? el : closest(el.parentNode, fn) );
        };

        // triggers when user clicks on thumbnail
        var onThumbnailsClick = function(e) {
            e = e || window.event;
            e.preventDefault ? e.preventDefault() : e.returnValue = false;

            var eTarget = e.target || e.srcElement;

            // find root element of slide
            var clickedListItem = closest(eTarget, function(el) {
                return (el.tagName && el.tagName.toUpperCase() === 'FIGURE');
            });

            if(!clickedListItem) {
                return;
            }

            // find index of clicked item by looping through all child nodes
            // alternatively, you may define index via data- attribute
            var clickedGallery = clickedListItem.parentNode,
                childNodes = clickedListItem.parentNode.childNodes,
                numChildNodes = childNodes.length,
                nodeIndex = 0,
                index;

            for (var i = 0; i < numChildNodes; i++) {
                if(childNodes[i].nodeType !== 1) {
                    continue;
                }

                if(childNodes[i] === clickedListItem) {
                    index = nodeIndex;
                    break;
                }
                nodeIndex++;
            }



            if(index >= 0) {
                // open PhotoSwipe if valid index found
                openPhotoSwipe( index, clickedGallery );
            }
            return false;
        };

        // parse picture index and gallery index from URL (#&pid=1&gid=2)
        var photoswipeParseHash = function() {
            var hash = window.location.hash.substring(1),
            params = {};

            if(hash.length < 5) {
                return params;
            }

            var vars = hash.split('&');
            for (var i = 0; i < vars.length; i++) {
                if(!vars[i]) {
                    continue;
                }
                var pair = vars[i].split('=');
                if(pair.length < 2) {
                    continue;
                }
                params[pair[0]] = pair[1];
            }

            if(params.gid) {
                params.gid = parseInt(params.gid, 10);
            }

            return params;
        };

        var openPhotoSwipe = function(index, galleryElement, disableAnimation, fromURL) {
            var pswpElement = document.querySelectorAll('.pswp')[0],
                gallery,
                options,
                items;

            if (!pswpElement) {
                pswpElement = Render.create(`<div class="pswp" tabindex="-1" role="dialog" aria-hidden="true">
                    <div class="pswp__bg"></div>
                    <div class="pswp__scroll-wrap">
                        <div class="pswp__container">
                            <div class="pswp__item"></div>
                            <div class="pswp__item"></div>
                            <div class="pswp__item"></div>
                        </div>
                        <div class="pswp__ui pswp__ui--hidden">
                            <div class="pswp__top-bar">
                                <div class="pswp__counter"></div>
                                <button class="pswp__button pswp__button--close" title="Close (Esc)"></button>
                                <button class="pswp__button pswp__button--share" title="Share"></button>
                                <button class="pswp__button pswp__button--fs" title="Toggle fullscreen"></button>
                                <button class="pswp__button pswp__button--zoom" title="Zoom in/out"></button>
                                <div class="pswp__preloader">
                                    <div class="pswp__preloader__icn">
                                        <div class="pswp__preloader__cut">
                                            <div class="pswp__preloader__donut"></div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="pswp__share-modal pswp__share-modal--hidden pswp__single-tap">
                                <div class="pswp__share-tooltip"></div>
                            </div>
                            <button class="pswp__button pswp__button--arrow--left" title="Previous (arrow left)">
                            </button>
                            <button class="pswp__button pswp__button--arrow--right" title="Next (arrow right)">
                            </button>
                            <div class="pswp__caption">
                                <div class="pswp__caption__center"></div>
                            </div>
                        </div>
                    </div>
                </div>`);
                document.body.appendChild(pswpElement);
            }

            items = parseThumbnailElements(galleryElement);

            // define options (if needed)
            options = {

                // define gallery index (for URL)
                galleryUID: galleryElement.getAttribute('data-pswp-uid'),

                getThumbBoundsFn: function(index) {
                    // See Options -> getThumbBoundsFn section of documentation for more info
                    var thumbnail = items[index].el.getElementsByTagName('img')[0], // find thumbnail
                        pageYScroll = window.pageYOffset || document.documentElement.scrollTop,
                        rect = thumbnail.getBoundingClientRect();

                    return {x:rect.left, y:rect.top + pageYScroll, w:rect.width};
                }

            };

            // PhotoSwipe opened from URL
            if(fromURL) {
                if(options.galleryPIDs) {
                    // parse real index when custom PIDs are used
                    // http://photoswipe.com/documentation/faq.html#custom-pid-in-url
                    for(var j = 0; j < items.length; j++) {
                        if(items[j].pid == index) {
                            options.index = j;
                            break;
                        }
                    }
                } else {
                    // in URL indexes start from 1
                    options.index = parseInt(index, 10) - 1;
                }
            } else {
                options.index = parseInt(index, 10);
            }

            // exit if index not found
            if( isNaN(options.index) ) {
                return;
            }

            if(disableAnimation) {
                options.showAnimationDuration = 0;
            }

            // Pass data to PhotoSwipe and initialize it
            gallery = new PhotoSwipe( pswpElement, PhotoSwipeUI_Default, items, options);
            gallery.init();
        };

        // loop through all gallery elements and bind events
        // var galleryElements = document.querySelectorAll( gallerySelector );

        for(var i = 0, l = galleryElements.length; i < l; i++) {
            galleryElements[i].setAttribute('data-pswp-uid', i+1);
            galleryElements[i].onclick = onThumbnailsClick;
        }

        // Parse URL and open gallery if it contains #&pid=3&gid=1
        var hashData = photoswipeParseHash();
        // if(hashData.pid && hashData.gid) {
            openPhotoSwipe( hashData.pid ,  galleryElements[0], true, true );
        // }
    };

    function newInstance(data) {
        console.log(data);
        let Header = Component.header(data);
        let Info = Component.info({ ...data,
            onClickEdit: function (info) {
                console.log("info", info);

                function open() {
                    //清除签名画布
                    $('#signDialogBox').remove();
                    
                    let mediaBody = Component.mediaBody(info);
                    let media = Component.media({
                        title: "编辑表单",
                        body: mediaBody.el,
                        onComplete: function (exp, done) {
                            let md = mediaBody.el.__data;
                            if (Util.type(md) == "function") {
                                md = md();
                                if (Util.type(md) == "string") {
                                    Component.toast(md).render();
                                    return;
                                }
                            }
                            // 判断必填项
                            if (info.required && Util.isEmpty(md.value)) {
                                Component.toast(md.emptyTip || "请填写内容").render();
                                return;
                            }
    
                            // 新增验证
                            if (info.validate) {
                                let result = info.validate(md.value, md.value_text, info);
                                if (result !== true) {
                                    Component.toast(result).render();
                                    return;
                                }
                                md.value = info.value;
                                md.value_text = info.value_text;
                            }
    
                            // 云盘数据为json
                            if (info.type == "netdisk") {
                                info.value = JSON.stringify(md.value);
                                info.value_text = JSON.stringify(md.value);
                            } else if (Util.type(md.value) == "array") {
                                info.value = md.value.join(",");
                                info.value_text = md.value_text.join(",");
                            } else {
                                info.value = md.value;
                                info.value_text = md.value_text;
                            }
                            
                            // 更新选项关联
                            // setRelations(info);
                            
                            // 如果修改的时单选框，对其关联项进行显示隐藏
                            if (info.type == "options" || info.type == "multiOptions") {

                                // 首先将所有关联项隐藏
                                info.options_control.map(id => {
                                    if (data.info_maps[`${id}_${info.index}`]) {
                                        data.info_maps[`${id}_${info.index}`].display = false;
                                    }
                                });

                                // 针对多选下拉框对value处理成数组形式
                                info.value_text.split(',').forEach(function (value) {
                                    // 然后对当前关联项进行显示
                                    if (info.options.hasOwnProperty(value)) {
                                        info.options[value].map(id => {
                                            if (data.info_maps[`${id}_${info.index}`]) {
                                                data.info_maps[`${id}_${info.index}`].display = true;
                                            }
                                        });
                                    }
                                })
                                
                            }
                            done();
                        }
                    }).render();
                }

                if (info.pre) {
                    info.pre(function (data) {
                        info.preData = data;
                        open();
                    });
                } else {
                    open();
                }
            }
        });
        let Process = Component.process({
                ...data,
                onReply: function (D_id, A_id, message) {
                    message = message.trim();
                    if (message == "") {
                        Component.toast("请输入回复内容").render();
                        return;
                    }
                    Api.approvalLeaveMessage({approval_identity: data.approval_identity, student_id: data.student_id, D_id, A_id, message}, function (result) {
                        Component.toast("回复成功").render(function () {
                            location.reload();
                        });
                    });
                }
            });

        if (data.is_creator) {
            var Opera = Component.opera({
                data: data,
                onTrash: function () {
                    if (!window.confirm("确定撤销审核吗？")) {
                        return false;
                    }

                    Api.revokeApproval({
                        D_id: data.D_id
                    }, function (result) {
                        Component.toast("操作成功").render(function () {
                            location.reload();
                        });
                    });
                },
                // 打开提醒
                onBell: function () {
                    if (!window.confirm("确定提醒此次审批吗？")) {
                        return false;
                    }

                    Api.sendApprovalUser({
                        D_id: data.D_id,
                    }, function (result) {
                        Component.toast("操作成功").render(function () {
                            location.reload();
                        });
                    });
                },
                // 再次发起
                onRetweet: function () {
                    Api.replyApprovalInfo({
                        D_id: data.D_id,
                        form_id: data.form_id,
                        model_id: data.model_id,
                        approval_identity: data.approval_identity
                    });
                },
                // 作废
                onClose: function () {
                    Component.confirm("是否作废审批？", function () {
                        Api.saveFormDetail({
                            form_id: data.form_id,
                            json: JSON.stringify(data.info_original),
                            D_id: data.D_id,
                            insert_stud_id: data.approval_identity == "0" ? data.student_id : ""
                        }, function () {
                            location.reload();
                        });
                    }).render();
                }
            });
        }

        // 将界面的表单数据整合到json中
        let unite = function (info, json, values) {
            info.map(item => {
                if (item.type == "part") {
                    unite(item.children, json[item.id].set, json[item.id].values);
                } else if (item.editable) {
                    // 不可修改的表单不放入值
                    let id = item.id.split("_").slice(-1)[0];
                    // 如果不是显示的表单项，清空内部的值
                    if (!item.display) {
                        json[id].value = '';
                        json[id].value_text = '';
                    } else if (Util.isEmpty(values)) {
                        // 如果有values，把值放入values中
                        json[id].value = item.value;
                        json[id].value_text = item.value_text;
                    } else {
                        var thisIndex = item.parent ? item.parentIndex : item.index;
                        values[thisIndex][id].value = item.value;
                        values[thisIndex][id].value_text = item.value_text;
                    }
                }
            });
        };

        if (data.assessor) {
            let el = Component.complain(data).el;
            let prefix_title = data.complain_required ? "<span class='link-danger'>*</span> " : "";
            var Tabbar = Component.tabbar(Object.assign(data, {
                onPass: function () {
                    Component.media({
                        title: prefix_title + "通过审批",
                        body: el,
                        onComplete: function (form, done) {
                            // 是否有必填项没填写的情况
                            for (let i = 0; i < data.info.length; i++) {
                                let info = data.info[i];
                                // 显示项 && 必填项 && 可编辑项 && 值不能为空
                                if (info.display && info.required && info.editable && Util.isEmpty(info.value)) {
                                    Component.toast(`${info.title}不能为空！`).render();
                                    return false;
                                }
                            }

                            // 限制必填审批意见
                            if (data.complain_required && form.complain == "") {
                                Component.toast("请填写审批意见").render();
                                return false;
                            }

                            // 保存json数据
                            let json = JSON.parse(JSON.stringify(data.info_original));
                            unite(data.info, json);

                            Component.confirm("是否同意审批？", function () {
                                done();
                                Api.approval({
                                    D_id: data.D_id,
                                    A_id: data.A_id,
                                    AD_id: data.AD_id,
                                    pass: "1",
                                    complain: form.complain,
                                    formDetailJson: JSON.stringify(json)
                                }, function (result) {
                                    location.reload();
                                });
                            }).render();

                        }
                    }).render();
                },
                onRefuse: function () {
                    Component.media({
                        title: prefix_title + "拒绝审批",
                        body: el,
                        onComplete: function (form, done) {
                            if (data.complain_required && form.complain == "") {
                                Component.toast("请填写审批意见").render();
                                return false;
                            }

                            // 保存json数据
                            let json = JSON.parse(JSON.stringify(data.info_original));
                            unite(data.info, json);

                            Component.confirm("是否拒绝审批？", function () {
                                done();
                                Api.approval({
                                    D_id: data.D_id,
                                    A_id: data.A_id,
                                    AD_id: data.AD_id,
                                    pass: "0",
                                    complain: form.complain,
                                    formDetailJson: JSON.stringify(json)
                                }, function (result) {
                                    location.reload();
                                });
                            }).render();
                        }
                    }).render();
                }
            }));
        }

        // 加载组件
        let Container = Render.getContainer('app');
        Container.append(Header, Info, Process);
        
        if (data.warning_label != "") {
            Container.append(Component.warningText({
                text: data.warning_label,
                type: "danger"
            }));
        }

        if (data.is_creator) {
            Container.append(Opera);
        }

        if (data.assessor) {
            Container.append(Tabbar);
        }

        // +yk: 添加印章
        let Stamp = Component.stamp(data.approval_status);
        if (Stamp) {
            Container.append(Stamp);
        }

        if (data.invalid_id !== false) {
            Api.getStartApprovalInfo({
                D_id: data.invalid_id
            }, function (result) {
                let detail = getDetail(result.data);

                Process.el.after(Component.process({
                    title: "作废流程",
                    process: detail.process || [],
                    onReply: function (D_id, A_id, message) {
                        message = message.trim();
                        if (message == "") {
                            Component.toast("请输入回复内容").render();
                            return;
                        }
                        Api.approvalLeaveMessage({approval_identity: data.approval_identity, student_id: data.student_id, D_id, A_id, message}, function (result) {
                            Component.toast("回复成功").render(function () {
                                location.reload();
                            });
                        });
                    }
                }).el);
            });
        }

        // 修改单选多选对其关联项进行显示隐藏
        function setRelations(info) { 
            if (info.type != "options" && info.type != "multiOptions") {
                return
            }
            if (info.options_control.length === 0) {
                return
            }
            var values_obj = {}, // 用于存储所有表单项的value和value_text
                hidden_keys = [].concat(info.options_control), // 用于存储即将被隐藏的项
                current_keys = [], // 用于存储即将显示的项
                current_obj = {} // 去重用

                for (let i in data.info_maps) {
                    values_obj[i] = {
                        value: data.info_maps[i].value,
                        value_text: data.info_maps[i].value_text
                    }
                }

                info.value.split(',').map(val => {
                    if (info.original.type == "4") {
                        if (info.options[val]) {
                            info.options[val].map(infoVal => {
                                current_obj[infoVal] = infoVal
                            })
                        }
                    } else if (info.original.type == "5") {
                        if (info.options_values[val]) {
                            info.options_values[val].map(infoVal => {
                                current_obj[infoVal] = infoVal
                            })
                        }
                    }
                })
                for (let i in current_obj) {
                    current_keys.push(current_obj[i])
                }
                current_keys.map(k => {
                    if (~hidden_keys.indexOf(k)) {
                        hidden_keys.splice(hidden_keys.indexOf(k), 1)
                    }
                })

            
            
            // 首先将所有关联项隐藏
            info.options_control.map(id => {
                if (data.info_maps[`${id}_${info.index}`]) {
                    data.info_maps[`${id}_${info.index}`].display = false;
                    data.info_maps[`${id}_${info.index}`].value = '';
                    data.info_maps[`${id}_${info.index}`].value_text = '';
                }
            });
            
            
            /**
             * 先获取选中的链表
             * 在已有的链表规则中寻找当前操作获取的链表 
             * 
             * */ 
            
            
            var keysArr = data.relationLines.keys,
                keysObj = {},
                ownKeyName = info.id,
                disabledRelationLines = data.relationLines.disabledRelationLines,
                isLineHead = false,
                changeOwnkeys = key => {
                    return info.parent ? key.replace(/(\d+)_(\d+)/, '$1_'+ info.parentIndex +'_$2') : key // 转换自增明细内的
                }
            // 明细内
            if (info.parent) {
                disabledRelationLines = data.relationLines.disabledOwnRelationLines
                keysArr = data.relationLines.ownKeys
                ownKeyName = [info.parent, info.parentIndex, info.id].join('_')
            }

            for (let i = 0, len = disabledRelationLines.length; i < len; i++) {
                let line = disabledRelationLines[i].map(item => changeOwnkeys(item))
                if (line.indexOf(ownKeyName) === 0) {
                    isLineHead = true
                }
                disabledRelationLines[i].map((t, index) => {
                    if (index > 0) {
                        t = changeOwnkeys(t)
                        let i = 0
                        while(true) {
                            if (!data.info_maps[t + '_' + i]) {
                                break
                            }
                            data.info_maps[t + '_' + i].display = false;
                            data.info_maps[t + '_' + i].value = '';
                            data.info_maps[t + '_' + i].value_text = '';
                            i += 1
                        }
                    }
                })
            }
            
            keysArr.map(function (item) {
                var itemIndex = item.indexOf(ownKeyName);
                // 过滤删除
                if (~itemIndex) {
                    if (~hidden_keys.indexOf(item[itemIndex + 1])) {
                        item.splice(itemIndex + 1);
                    }
                }
    
                keysObj[JSON.stringify(item)] = item;
            }); // 去重
            
            keysArr.length = 0;

            for (var i in keysObj) {
                if (keysObj[i].length > 1) {
                    keysArr.push(keysObj[i]);
                }
            }
            if (isLineHead) {
                current_keys.forEach(key => {
                    keysArr.push([ownKeyName].concat(key))
                })
            } else {
                // 去重
                keysArr.length = 0 
                for (var i in keysObj) {
                    keysArr.push(keysObj[i])
                }
                var tempPushLine = [] // 即将加入的链表
                keysArr.map(item => {
                    let itemIndex = item.indexOf(ownKeyName)
    
                    if (~itemIndex) {
                        for (let i = 1, len = current_keys.length; i < len; i++) {
                            tempPushLine.push([].concat(item).push(current_keys[i]))
                        }
                        item.push(current_keys[0])
                    }
                })
                keysArr.concat(tempPushLine)
            }
            
            disabledRelationLines.forEach(item => {
                keysArr.map(line => {
                    let ownItem = item.map(k => changeOwnkeys(k))
                    if (ownItem.join(',').indexOf(line.join(',')) === 0) {
                        line.map(t => {
                            let i = 0
                            while(true) {
                                if (!data.info_maps[t + '_' + i]) {
                                    break
                                }
                                data.info_maps[t + '_' + i].display = true;
                                data.info_maps[t + '_' + i].value = values_obj[t + '_' + i].value
                                data.info_maps[t + '_' + i].value_text = values_obj[t + '_' + i].value_text
                                i += 1
                            }
                        })
                    }
                })
            })
            
            // 针对多选下拉框对value处理成数组形式
            info.value_text.split(',').forEach(function (value) {
                // 然后对当前关联项进行显示
                if (info.options.hasOwnProperty(value)) {
                    info.options[value].map(id => {
                        if (data.info_maps[`${id}_${info.index}`]) {
                            // data.info_maps[`${id}_${info.index}`].display = true;
                        }
                    });
                }
            })
            
            
        }

        Container.render();
    }

    function getDetail(data) {
        let detail = {
            A_id: QUERY.a,
            D_id: data.formDetail.id,
            AD_id: QUERY.ad,
            approval_identity: data.formDetail.identity,
            student_id: data.formDetail.insert_user == Config.user.id ? data.formDetail.insert_stud_id : "", 
            form_id: data.formDetail.form_id,
            model_id: data.formDetail.model_id,
            avatar: data.formDetail.head_url || Config.default_avatar,
            name: data.formDetail.startUserName,
            mobile: data.formDetail.startMobile,
            info: JSON.parse(data.formDetail.json),
            info_original: JSON.parse(data.formDetail.json),
            process: data.formApprovalList,
            // 1正在审批 2审批通过 3审批拒绝 4审批撤销
            status: data.formDetail.formApprovalDetailStatus + "",
            // +yk: 是否为审核员，用来展示按钮用
            assessor: (function (formDetail) {
                return formDetail.formApprovalDetailStatus == 1
                    && formDetail.approval_status == 1
                    && formDetail.formApprovalStatus == 1
                    && !formDetail.invalid_id
            })(data.formDetail),
            // ＋yk: 是否为创作者
            is_creator: data.formDetail.insert_user == Config.user.id,
            creator_id: data.formDetail.insert_user,
            node: undefined,
            // 审批意见是否必填
            complain_required: data.formDetail.approvalIsRequired == 1,
            // 审批意见是否对发起人可见
            complain_visible: true,
            warning_label: "",
            // 1正在审批 2审批通过 3审批拒绝 4审批撤销
            approval_status: data.formDetail.approval_status + "",
            // 审批意见提示文字
            approval_tips: Util.isEmpty(data.formDetail.approvalTips) ? "" : data.formDetail.approvalTips,
            // 作废ID
            invalid_id: data.formDetail.invalid_id || false,
            // 是否已作废
            is_invalid: data.formDetail.is_invalid == 1,
            // 教职考勤 2
            category: data.formDetail.category,
            //年级名称
            grade_name: data.formDetail.startGradeName,
            //班级名称
            class_name: data.formDetail.startClassName

        };

        // 审批意见是否对发起人可见 approvalIsHidden 0显示 1隐藏
        // 判断是否不为发起人，否则判断是否可见
        detail.complain_visible = !detail.is_creator || data.formDetail.approvalIsHidden == 0;

        // ＋yk: 状态为5添加警告文字
        if (data.formDetail.approval_status == 5) {
            detail.warning_label = "因流程设置异常，该审批流程无法通过，请联系学校管理人员修改！";
        }

        // 追加当前查看节点
        try {
            let approval = JSON.parse(data.formDetail.approval);
            data.formDetail.node.trim().split(",").map(n => {
                if(n != "") approval = approval[n];
            });
            detail.node = approval;
        } catch (error) {
            console.error("approval查找node失败");
        }

        // 追加编辑权限，只放入可编辑的index
        let auth = {};
        // if (detail.node != undefined && detail.assessor) {
        //     for (let index in detail.node.auth) {
        //         if (detail.node.auth[index] == "1") {
        //             auth.push(index);
        //         }
        //     }
        // }

        let _authProcess = function (process) {
            let ele = {};
            if (process.hasOwnProperty("approvalEleJson") && !Util.isEmpty(process.approvalEleJson)) {
                ele = JSON.parse(process.approvalEleJson);
            }

            if (!Util.isEmpty(ele.auth)) {
                for(let key in ele.auth) {
                    if (auth[key]) {
                        if (ele.auth[key] == "1" && ["2", "3"].includes(auth[key] + "")) {
                            continue;
                        }
                        if (ele.auth[key] == "2" && ["3"].includes(auth[key] + "")) {
                            continue;
                        }
                    }
                    auth[key] = ele.auth[key] + "";
                }
            }
        };

        // 处理显示权限
        // 查询到隐藏时添加隐藏属性，否则都可看
        // assessor=true时为先天条件
        let reverse = [].concat(detail.process).reverse();
        if (detail.assessor && !detail.is_invalid) {
            _authProcess(reverse[0]);
        } else {
            reverse = reverse.slice(1);
            for (let index in reverse) {
                let process = reverse[index];
                if (Util.isEmpty(process.user_id)) {
                    break;
                }
                if (!process.user_id.split(",").includes(Config.user.id)) {
                    break;
                }
                _authProcess(process);
            }
            // 1权限变为2只读权限
            for (let i in auth) {
                if (auth[i] == "1") {
                    auth[i] = "2";
                }
            }
        }

        // 处理详情
        detail.info_maps = {};
        detail.info = (function compileInfo (info, value = {}, editable = false, parent = "", parentIndex = 0) {
            let  _info = [];

            if (!Util.isEmpty(value)) {
                for (let i in value) {
                    info[i].value = value[i].value;
                    info[i].value_text = value[i].value_text;
                }
            }

            Util.likeItemObjectMap(info, function (item, index) {
                // 权限隐藏
                if (auth[index] == "3" && parent === "") {
                    return true;
                }

                item = JSON.parse(JSON.stringify(item));

                if (item.type == "9" && item.is_show == false) {
                    return true;
                }

                let __infos = [];

                switch(item.type + "") {
                    case "4":
                        let maps4 = {};
                        // 该单选框控制的其他表单项id
                        let controls4 = [];
                        Util.likeItemObjectMap(item.options, function (option) {
                            maps4[option.text] = option.relation.map(r => {
                                r += "";
                                if (parent !== "") {
                                    r = [parent, parentIndex, r].join('_')
                                    // r = parent + '_' + parentIndex + '_' + index + '_' + r;
                                }
                                if (!controls4.includes(r)) {
                                    controls4.push(r);
                                }
                                return r;
                            });
                        });

                        __infos.push({
                            id: index + "",
                            index: 0,
                            parentIndex: parentIndex,
                            parent: parent,
                            title: item.title,
                            placeholder: item.placeholder,
                            type: "options",
                            value: item.value,
                            value_text: item.value_text,
                            original: item,
                            editable: editable || auth[index] == "1",
                            required: item.is_force,
                            options: maps4,
                            options_control: controls4
                        });
                        break;
                    case "5":
                        let maps5 = {}, mapsValues = {};
                        // 该多选框控制的其他表单项id
                        let controls5 = [];
                        Util.likeItemObjectMap(item.options, function (option, index) {
                            maps5[option.text] = option.relation.map(r => {
                                r += "";
                                if (parent !== "") {
                                    r = parent + '_' + r;
                                }
                                if (!controls5.includes(r)) {
                                    controls5.push(r);
                                }
                                return r;
                            });
                            mapsValues[index] = maps5[option.text]
                        });

                        __infos.push({
                            id: index + "",
                            index: 0,
                            parentIndex: parentIndex,
                            parent: parent,
                            title: item.title,
                            placeholder: item.placeholder,
                            type: "multiOptions",
                            value: item.value,
                            value_text: item.value_text,
                            original: item,
                            editable: editable || auth[index] == "1",
                            required: item.is_force,
                            options: maps5,
                            options_control: controls5,
                            options_values: mapsValues
                        });
                        break;
                    case "7":
                        __infos.push({
                            id: index + "",
                            index: 0,
                            parentIndex: parentIndex,
                            parent: parent,
                            title: item.title,
                            placeholder: item.placeholder,
                            type: "image",
                            value: item.value,
                            value_text: item.value_text,
                            original: item,
                            editable: editable || auth[index] == "1",
                            required: item.is_force,
                            max_image_length: item.uploadImgNumber == "只可上传一张" ? 1 : 9,
                            source_type: item.uploadImgWay == "拍照或本地上传" ? ['album', 'camera'] : ['camera'],
                        });
                        break;
                    case "71":
                        //手写签名
                        __infos.push({
                            id: index + "",
                            index: 0,
                            parent: parent,
                            parentIndex: parentIndex,
                            title: item.title,
                            placeholder: item.placeholder,
                            type: "sign",
                            value: item.value,
                            value_text: item.value_text,
                            original: item,
                            editable: editable || auth[index] == "1",
                            required: item.is_force
                        });
                        break;
                    case "8":
                        // 附件
                        __infos.push({
                            id: index + "",
                            index: 0,
                            parentIndex: parentIndex,
                            parent: parent,
                            title: item.title,
                            placeholder: item.placeholder,
                            type: "netdisk",
                            value: item.value,
                            value_text: item.value_text,
                            original: item,
                            editable: editable || auth[index] == "1",
                            required: item.is_force
                        });
                        break;
                    case "99":
                        item.values.map((value, i) => {
                            __infos.push({
                                id: index + "",
                                index: i,
                                parentIndex: parentIndex,
                                parent: parent,
                                title: item.title,
                                type: "part",
                                original: item,
                                children: compileInfo(item.set, value, auth[index] == "1", index + "", i),
                                editable: editable || auth[index] == "1"
                            });
                        });
                        break;
                    case "9":
                        __infos.push({
                            id: index + "",
                            index: 0,
                            parentIndex: parentIndex,
                            parent: parent,
                            title: item.title,
                            placeholder: item.placeholder,
                            type: "text",
                            value: item.value,
                            value_text: item.value_text,
                            original: item,
                            editable: false,
                            required: item.is_force
                        });
                        break;
                    case "31":
                        __infos.push({
                            id: index + "",
                            index: 0,
                            parentIndex: parentIndex,
                            parent: parent,
                            title: item.title,
                            placeholder: item.placeholder,
                            type: "tel",
                            value: item.value,
                            value_text: item.value_text,
                            original: item,
                            editable: editable || auth[index] == "1",
                            required: item.is_force,
                            validate: function (value, value_text, data) {
                                if (value == "") {
                                    data.value = value;
                                    data.value_text = value_text;
                                    return true;
                                }
                                if (!(/^1[0-9]{10}$/.test(value))) {
                                    return "手机号格式错误！";
                                }
                                data.value = value;
                                data.value_text = value_text;
                                return true;
                            }
                        });
                        break;
                    case "32":
                        __infos.push({
                            id: index + "",
                            index: 0,
                            parentIndex: parentIndex,
                            parent: parent,
                            title: item.title,
                            placeholder: item.placeholder,
                            type: "id",
                            value: item.value,
                            value_text: item.value_text,
                            original: item,
                            editable: editable || auth[index] == "1",
                            required: item.is_force,
                            validate: function (value, value_text, data) {
                                if (value == "") {
                                    data.value = value;
                                    data.value_text = value_text;
                                    return true;
                                }
                                var val = value;
                                var isRight = false;
                                if ($.trim(val).length === 18) {
                                    if (isNaN(+val.substring(0, 17))) {
                                        isRight = false;
                                    } else {
                                        if (val.substring(17, 18) !== 'x' && val.substring(17, 18) !== 'X' && isNaN(+val.substring(17, 18))) {
                                            isRight = false;
                                        } else {
                                            isRight = true;
                                        }
                                    }
                                }
                                if (!isRight) {
                                    return '身份证号格式错误！';
                                }

                                data.value = value.replace('x', 'X');
                                data.value_text = value_text.replace('x', 'X');

                                return true;
                            }
                        });
                        break;
                    case "33": 
                        __infos.push({
                            id: index + "",
                            index: 0,
                            parentIndex: parentIndex,
                            parent: parent,
                            title: item.title,
                            placeholder: item.placeholder,
                            type: "text",
                            value: item.value,
                            value_text: item.value_text,
                            original: item,
                            editable: editable || auth[index] == "1",
                            required: item.is_force,
                            warning: item.warning
                        })
                        break;
                    case "51":
                        __infos.push({
                            id: index + "",
                            index: 0,
                            parentIndex: parentIndex,
                            parent: parent,
                            title: item.title,
                            placeholder: item.placeholder,
                            type: "address",
                            value: item.value,
                            value_text: item.value_text,
                            original: item,
                            editable: editable || auth[index] == "1",
                            required: item.is_force,
                            pre: function (done) {
                                Api.getAddress({}, function (data) {
                                    done(data);
                                }, function (e) {
                                    console.log(e);
                                });
                            },
                            preData: {}
                        });
                        break;
                    case "71":
                        __infos.push({
                            id: index + "",
                            index: 0,
                            parentIndex: parentIndex,
                            parent: parent,
                            title: item.title,
                            placeholder: item.placeholder,
                            type: "sign",
                            value: item.value,
                            value_text: item.value_text,
                            original: item,
                            editable: editable || auth[index] == "1",
                            required: item.is_force,
                        });
                        break;
                    default:
                        // +yk: 判断数字输入框，然后title后面追加单位unit文字
                        if (item.type == "3" && !Util.isEmpty(item.unit)) {
                            item.title += "（" + item.unit + "）";
                        }

                        __infos.push({
                            id: index + "",
                            index: 0,
                            parentIndex: parentIndex,
                            parent: parent,
                            title: item.title,
                            placeholder: item.placeholder,
                            type: "text",
                            value: item.value,
                            value_text: item.value_text,
                            original: item,
                            editable: editable || auth[index] == "1",
                            required: item.is_force,
                            date_type: item.dateType || "",
                            is_hidden: item.is_hidden || false
                        });
                }

                __infos.map(__info => {
                    // 添加显示隐藏
                    if (Util.isEmpty(item.relationed) || Util.type(item.relationed) == "array" && item.relationed.length == 1 && item.relationed[0] == 0) {
                        // 未关联直接显示
                        __info.display = true;
                        __info.relationed = [];
                    } else {
                        // 已关联先隐藏
                        __info.display = false;
                        __info.relationed = item.relationed.map(r => r + "");
                    }
                    
                    _info.push(__info);

                    if (!parent) {
                        detail.info_maps[`${__info.id}_${__info.index}`] = __info;
                    } else {
                        detail.info_maps[`${parent}_${parentIndex}_${__info.id}_${__info.index}`] = __info;
                    }
                });

            });

            // 将所有的单选框关联项打开
            _info.map(__info => {
                if (__info.type == "options" || __info.type == "multiOptions" ) {
                    __info.value_text.split(',').forEach(function (value) {
                        if (__info.options.hasOwnProperty(value)) {
                            __info.options[value].map(r => {
                                let i = 0;
                                // 解决遍历明细造成info_maps数据错乱情况
                                let key = `${r}_${i}`;
                                // if (parent) {
                                //     key = `${parent}_${r}_${i}`;
                                // }
                                while (detail.info_maps.hasOwnProperty(key)) {
                                    detail.info_maps[key].display = true;
    
                                    i++;
                                    key = `${r}_${i}`;
                                    // if (parent) {
                                    //     key = `${parent}_${r}_${i}`;
                                    // }
                                }
                            });
                        }
                    })
                }
            });

            return _info;
        })(detail.info);

        // 定义将要选项关联的keys
        detail.relationLines = {
            keys: [],
            ownKeys: [],
            disabledOwnRelationLines: detail.info_original.others.disabledOwnRelationLines.map(item => item.map(i => i + "")),
            disabledRelationLines:detail.info_original.others.disabledRelationLines.map(item => item.map(i => i + "")),
        }

        // 包含单选框的详情初始显示数据修改
        detail.info.map(info => {
            let map = `${info.id}_${info.index}`;
            if (info.type != "options" && info.type != "multiOptions") {
                return true;
            }

            info.value.split(",").forEach(function (value) {
                if (info.options.hasOwnProperty(value)) {
                    info.options[value].map(id => {
                        if (detail.info_maps[`${id}_${info.index}`]) {
                            detail.info_maps[`${id}_${info.index}`].display = true;
                        }
                    });
                }
            })

        });

        // 处理流程
        detail.process = detail.process.map((process, index) => {
            let persons = process.formApprovalDetailList.map(person => {
                return {
                    andor: person.andor || "",
                    avatar: person.head_url || "",
                    name: person.user_name,
                    status: person.detail_status,
                    complain: person.content || "",
                    readed: person.is_read == 1
                };
            });
            let person = persons[0],
                person_count = persons.length;

            if (person == undefined) {
                person = {};
            }

            let andor_text = {1:"(会签)",2:"(或签)"}[person.andor] || "";

            let ele = {};
            if (process.hasOwnProperty("approvalEleJson") && !Util.isEmpty(process.approvalEleJson)) {
                ele = JSON.parse(process.approvalEleJson);
            }

            let result = {
                D_id: process.formDetailId,
                A_id: process.formApprovalId,
                persons: persons,
                title: ele.title,
                avatar: person.avatar || Config.default_avatar,
                name: (person.name || "") + (person_count > 1 ? "等"+ person_count +"人" + andor_text : ""),
                time: (process.type == 2 ? ((process.status == 2 || process.status == 3) ? process.approvalTimeStr : "") : process.insertTimeStr),
                status: (function (status) {
                    let _status = {
                        "1": "approval",
                        "2": "success",
                        "3": "refuse"
                    };
                    return _status[status];
                })(process.status + ""),
                type: (function (type) {
                    let _type = {
                        "1": "copy",
                        "2": "approval"
                    }
                    return index == 0 ? "original" : (_type[type] || "");
                })(process.type + ''),
                type_text: "",
                label: "",
                // 留言
                reply: (function (message_list, complain_visible) {
                    let replys = [];
                    message_list.map(message => {
                        // 先判断是否对发起人可见，如果不可见，仅获取发起人的留言内容
                        if (complain_visible || detail.creator_id == message.user_id) {
                            replys.push({
                                id: message.formApprovalMessageId + "",
                                reply: message.content,
                                name: message.user_name
                            });
                        }
                    });
                    return replys;
                })(process.formApprovalMessageList, detail.complain_visible),
                // 审批意见
                complain: (function (persons, complain_visible) {
                    let complains = [];
                    persons.map(person => {
                        // 先判断是否对发起人可见，如果不可见，仅获取发起人的留言内容
                        if (complain_visible || detail.creator_id == person.user_id) {
                            if (person.complain) {
                                complains.push({
                                    name: person.name,
                                    content: person.complain
                                });
                            }
                        }
                    });
                    return complains;
                })(persons, detail.complain_visible)
            };

            result.type_text = (function (type) {
                let _type = {
                    copy: "抄送人",
                    approval: "审批人",
                    original: "发起人"
                };
                return _type[type] || "";
            })(result.type);

            if (result.type == "original") {
                result.label = "";
            } else if (result.type == "copy") {
                let readed = 0;
                process.formApprovalDetailList.map(item => {
                    if (item.is_read == 1) {
                        readed += 1;
                    }
                });
                result.label = readed + "人已读";
            } else if (result.status == "approval") {
                result.label = "审批中";
            } else if (result.status == "success") {
                result.label = "已通过";
            } else if (result.status == "refuse") {
                result.label = "已拒绝";
            }

            return result;
        });

        if (data.formDetail.node == "end") {
            detail.process.push({
                end: true
            });
        }

        return detail;
    }

    Init.prototype.instance = function () {
        // 解决当预览过程中刷新页面时造成的后退多次才能生效的问题
        if (location.hash.slice(1) != "") {
            history.back();
        }

        Api.getApprovalInfo({
            AD_id: QUERY.ad
        }, function (result) {
            if (Util.type(result.data.formDetail) == 'null' || result.data.formDetail + "" == "") {
                Component.toast('数据不存在').render();
                return false;
            }

            // +yk: 列表页返回刷新
            sessionStorage.setItem("approvalDetailChanged", "changed");

            // 整理数据
            let detail = getDetail(result.data);

            newInstance(detail);
        });
    };

    return new Init;
})();

if (Util.isEmpty(BASE.TOKEN)) {
    getUserLoginBaseInfoOfOpenid(QUERY.openid, QUERY.org_id, QUERY.identity, function (data) {

        Config.user.token = BASE.TOKEN = data.token;
        Config.user.udid = BASE.UDID = data.udid;
        Config.user.id = BASE.USER_ID = data.orguser.user_id + "";
        Config.user.org_id = BASE.ORG_ID = data.orguser.org_id;

        // 初始化执行
        Api.jssdkRegister(function () {
            Init.instance();
        });
    }, true);
} else {
    // 初始化执行
    Api.jssdkRegister(function () {
        Init.instance();
    });
}




